package com.ccteam.fluidmusic.ui.artist

import androidx.lifecycle.*
import com.ccteam.fluidmusic.utils.setValueIfNew
import com.ccteam.fluidmusic.view.bean.ErrorMessage
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.model.Resource
import com.ccteam.model.artist.ArtistVO
import com.ccteam.shared.domain.artist.ArtistDetailInfoDataUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/2/20
 *
 * 歌手详情页ViewModel
 */
@HiltViewModel
class ArtistDetailViewModel @Inject constructor(
    private val artistDetailInfoDataUseCase: ArtistDetailInfoDataUseCase,
    savedStateHandle: SavedStateHandle
): ViewModel() {

    /**
     * 网络请求专辑信息后存储的内容，用它来将 [loadMessage]
     */
    private val artistInfoResult = MutableLiveData<Resource<ArtistVO?>>(Resource.Loading(null))

    private val _artistInfo = MediatorLiveData<ArtistVO?>()
    val artistInfo: LiveData<ArtistVO?> get() = _artistInfo

    private val artistId = MutableLiveData<String>()

    val loadMessage: LiveData<LoadMessage> = artistInfoResult.map {
        when(it){
            is Resource.Success ->{
                if(it.data == null){
                    LoadMessage.Empty
                } else {
                    LoadMessage.NotLoading
                }
            }
            is Resource.Loading ->{
                LoadMessage.Loading
            }
            is Resource.Error ->{
                LoadMessage.Error(ErrorMessage(it.message,it.errorCode))
            }
        }
    }

    val showAppbar: LiveData<Boolean> = artistInfoResult.map {
        it is Resource.Success
    }

    init {
        _artistInfo.addSource(artistId){
            refreshArtistInfo()
        }

        artistId.setValueIfNew(savedStateHandle["artistId"])
    }

    fun refreshArtistInfo(){
        artistId.value?.let {
            viewModelScope.launch {
                artistDetailInfoDataUseCase(it).collectLatest {
                    artistInfoResult.value = it

                    _artistInfo.value = it.data
                }
            }
        }
    }

}